﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using LongNet.Util;
using System.IO;

using LongNet.Security;

namespace LongNet.Config
{
    /// <summary>
    /// Includes some convenient configuration extensions.
    /// </summary>
    public static class ConfigManager
    {
        #region Fields
        //文件路径
        public static readonly string LongNetConfigPath;
        //配置文件夹路径
        public static readonly string LongNetConfigFolder;
       
        public static readonly IFileConfigManager<LongNetConfigEntity> LongNetConfig;

        #endregion

        #region Constructor

        static ConfigManager()
        {
            string folder = ConfigurationManager.AppSettings.GetString("LongNet.ConfigFolder");
            try
            {
                folder = Utils.GetFullPath(folder);
                var dir = new DirectoryInfo(folder);
                if (!dir.Exists)
                {
                    dir.Create();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
         
            LongNetConfigPath = folder + "\\LongNet.config";
            LongNetConfigFolder = folder;
            LongNetConfig = FileConfigManager.CreateManager(ConfigMonitorType.Watcher, LongNetConfigPath, new LongNetConfigEntity());

            // 添加默认的管理员
            if (LongNetConfig.GetConfig().Users.Count == 0)
            {
                var config = LongNetConfig.GetConfig();
                string salt = CryptoService.CreateSaltToHexString(16);
                config.Users.Add(new UserConfigEntity()
                {
                    UserName = "long",
                    Salt = salt,
                    Password = CryptoService.ComputeHashToHexString("admin888" + salt, CryptoService.CryptoAlgorithm.SHA1)
                });

                LongNetConfig.SaveConfig();
            }
        }

        #endregion
    }
}
